package com.sync.utils.project.gasStatistics.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sync.utils.common.base.service.impl.BaseServiceImpl;
import com.sync.utils.project.gasStatistics.agent.GasAgent;
import com.sync.utils.project.gasStatistics.mapper.GasDayMapper;
import com.sync.utils.project.gasStatistics.mapper.GasMonthMapper;
import com.sync.utils.project.gasStatistics.pojo.*;
import com.sync.utils.project.gasStatistics.service.GasService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * TODO
 *
 * @Author YWF
 * @Date 2025/3/15 21:55
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(rollbackFor = Exception.class)
public class GasServiceImpl extends BaseServiceImpl<GasMonthMapper, GasMonthDto> implements GasService {

    @Autowired
    private GasMonthMapper gasMonthMapper;

    @Autowired
    private GasDayMapper gasDayMapper;

    @Autowired
    private GasAgent gasAgent;

    @Override
    @Async("asyncServiceExecutor")
    public void taskGasMonthBillList() {
        // 查询数据库已存在记录的最大月份和最小月份
        GasMonthRecord gasMonth = gasMonthMapper.getGasMonth();
        GasMonthReq gasReq = new GasMonthReq();
        gasReq.setUserCode("2123805357");
        gasReq.setCid("5000000961");
        gasReq.setStartMonth(Objects.isNull(gasMonth) ? "202001" : gasMonth.getMaxMonth());
        gasReq.setEndMonth(DateUtil.date().toString("yyyyMM"));
        gasReq.setLengthTimeYqqs(2);
        gasReq.setPage(1);
        gasReq.setPageSize(10);
        List<GasMonthRes> recordsAll = new ArrayList<>();
        List<GasMonthRes> gasMonthBillList = getGasMonthBill(recordsAll, gasReq);
        if (CollectionUtil.isEmpty(gasMonthBillList)) {
            return;
        }
        if (!Objects.isNull(gasMonth) && gasMonth.getMaxMonth().equals(gasMonthBillList.get(0).getGasMonth())) {
            // 更新记录
            GasMonthRes gasRes = gasMonthBillList.get(0);
            GasMonthDto gasDto = BeanUtil.copyProperties(gasRes, GasMonthDto.class);
            LambdaUpdateWrapper<GasMonthDto> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(GasMonthDto::getGasMonth, gasRes.getGasMonth());
            gasMonthMapper.update(gasDto, lambdaUpdateWrapper);
        } else {
            // 插入记录
            List<GasMonthDto> gasDataList = BeanUtil.copyToList(gasMonthBillList, GasMonthDto.class);
            int counts = gasMonthMapper.batchGasMonthBill(gasDataList);
            System.out.println("插入结果：" + counts);
        }

    }

    @Override
    public List<GasMonthRes> getRemoteGasMonthBillList(GasMonthReq gasReq) {
        List<GasMonthRes> recordsAll = new ArrayList<>();
        List<GasMonthRes> gasMonthBillList = getGasMonthBill(recordsAll, gasReq);
        List<GasMonthDto> gasDataList = BeanUtil.copyToList(gasMonthBillList, GasMonthDto.class);
        // 数据入库
        int counts = gasMonthMapper.batchGasMonthBill(gasDataList);
        logger.info("入库条数：{}", counts);
        return gasMonthBillList;
    }

    private List<GasMonthRes> getGasMonthBill(List<GasMonthRes> recordsAll, GasMonthReq gasReq) {
        List<GasMonthRes> recordsInfo = gasAgent.getHttpGasMonthBillList(gasReq);
        List<GasMonthRes> filteredRecords = recordsInfo.stream().filter(record -> null != record.getGasVolume())
                .peek(record -> {
                    BigDecimal gasFee = new BigDecimal(record.getGasVolume());
                    BigDecimal monthMoney = gasFee.multiply(new BigDecimal(2.02)).setScale(2, RoundingMode.HALF_UP);
                    record.setGasMonth(DateUtil.format(DateUtil.parse(record.getGasYear() + "01"), "yyyyMM"));
                    record.setMonthMoney(monthMoney);
                }).collect(Collectors.toList());
        Optional<String> lastGasYearOptional = filteredRecords.stream().reduce((first, second) -> second).map(GasMonthRes::getGasYear);
        String lastGasYear = lastGasYearOptional.isPresent() ? lastGasYearOptional.get() : DateUtil.format(DateUtil.offsetMonth(DateUtil.parse(gasReq.getStartMonth(), "yyyyMM"), 7), "yyyy年MM月");
        DateTime lastEndMonth = DateUtil.parse(lastGasYear, "yyyy年MM月");
        DateTime endMonth = DateUtil.parse(gasReq.getEndMonth(), "yyyyMM");
        int result = DateUtil.compare(lastEndMonth, endMonth);
        recordsAll.addAll(filteredRecords);
        if (result < 0 && DateUtil.compare(lastEndMonth, endMonth) < 0 && DateUtil.compare(lastEndMonth, DateUtil.parse(DateUtil.date().toString("yyyyMM"), "yyyyMM")) < 0) {
            GasMonthReq gasReqTmp = new GasMonthReq();
            BeanUtil.copyProperties(gasReq, gasReqTmp);
            gasReqTmp.setStartMonth(DateUtil.format(DateUtil.offsetMonth(lastEndMonth, 1), "yyyyMM"));
            // 迭代循环
            getGasMonthBill(recordsAll, gasReqTmp);
        }
        return recordsAll;
    }

    @Override
    public List<GasDayRes> getRemoteGasDayBillList(String mdmCode, String userCode) {
        List<GasDayRes> recordsInfo = gasAgent.getHttpGasDayBillList(mdmCode, userCode).stream().filter(record->record.getGasVolume() != null).peek(record -> {
            BigDecimal gasVolume = new BigDecimal(record.getGasVolume());
            BigDecimal monthMoney = gasVolume.multiply(new BigDecimal(2.02)).setScale(2, RoundingMode.HALF_UP);
            record.setMonthMoney(monthMoney);
        }).collect(Collectors.toList());;
        return recordsInfo;
    }

    private List<GasDayRes> getGasDayBillList(List<GasDayRes> recordsInfo){
        GasDayRecord gasMaxDay = gasDayMapper.getGasDay();
        Stream<GasDayRes> gasDayResStream = null;
        if (ObjectUtil.isNull(gasMaxDay)) {
            gasDayResStream = recordsInfo.stream();
        } else {
            gasDayResStream = recordsInfo.stream().filter(record -> DateUtil.parse(record.getGasYear(), "yyyy/MM/dd").isAfter(DateUtil.parse(gasMaxDay.getMaxDay(), "yyyy/MM/dd")));
        }
        List<GasDayRes> recordsList = gasDayResStream.peek(record -> {
            BigDecimal gasVolume = new BigDecimal(record.getGasVolume());
            BigDecimal monthMoney = gasVolume.multiply(new BigDecimal(2.02)).setScale(2, RoundingMode.HALF_UP);
            record.setMonthMoney(monthMoney);
        }).collect(Collectors.toList());
        // 入库
        if (CollectionUtil.isNotEmpty(recordsList)){
            List<GasDayDto> gasDayDtoList = BeanUtil.copyToList(recordsList, GasDayDto.class);
            gasDayMapper.batchGasDayBill(gasDayDtoList);
        }
        return recordsList;
    }

    @Override
    @Async("asyncServiceExecutor")
    public void taskGasDayBillList() {
        List<GasDayRes> recordsInfo = gasAgent.getHttpGasDayBillList("9AX2", "2123805361");
        getGasDayBillList(recordsInfo);
    }

    @Override
    public GasUserRes getGasUserInfo(String userCode) {
        GasUserRes httpGasUserInfo = gasAgent.getHttpGasUserInfo(userCode);
        return httpGasUserInfo;
    }
}
